package com.teangtang.fly.service;
import com.teangtang.fly.entity.Admin;
import com.teangtang.fly.entity.Traveller;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class JWTService {
    private static long expire = 86400;
    private static String secret = "abcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefgh";

    public String generateAdminToken(Admin admin) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + 1000 * expire);
        Map<String, Object> claims = new HashMap<>();
        claims.put("userName", admin.getUsername());
        claims.put("userType", "admin");
        String token = Jwts.builder()
                .setHeaderParam("type", "JWT")
                .setClaims(claims)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
        return token;
    }

    public String generateTravellerToken(Traveller traveller) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + 1000 * expire);
        Map<String, Object> claims = new HashMap<>();
        claims.put("userName", traveller.getUsername());
        claims.put("userType", "traveller");
        String token = Jwts.builder()
                .setHeaderParam("type", "JWT")
                .setClaims(claims)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
        return token;
    }

    public static Claims getClaimsByToken(String token) {
        try {
            // 解析 token 并返回 Claims
            return Jwts.parser()
                    .setSigningKey(secret) // 使用正确的编码密钥
                    .parseClaimsJws(token)
                    .getBody();
        } catch (
                JwtException e) {
            // 如果 token 解析失败（无效、过期等），可能会抛出异常
            e.printStackTrace();
            return null;
        }
    }
}
